import { useState, useEffect } from "react";
import { Modal, Table } from "antd";
import type { ColumnsType } from "antd/es/table";
import { observer } from "Mobx-react";
import { modalState } from "@/stores/modalState";
import type { questionType, controlLogicType } from "@/types/index";

const columns: ColumnsType<questionType> = [
  {
    title: "题目标题",
    dataIndex: "title",
    key: "id",
    align: "center",
    render: (text: string) => <div dangerouslySetInnerHTML={{ __html: text }}></div>
  }
];
function ConcernCopy({ getCopy }: { getCopy: (childId: number[], data: controlLogicType[]) => void }) {
  const isCopy = modalState.isCopy;
  const [tableData, setTable] = useState<questionType[]>([]);
  const [childIds, setChildIds] = useState<number[]>([]);
  useEffect(() => {
    if (isCopy) {
      setTable(
        modalState.questions.concat().map(item => {
          delete item.children;
          return item;
        })
      );
      setChildIds([]);
    }
  }, [isCopy]);

  const onSelectChange = (sel: any[]) => {
    setChildIds(sel);
  };

  //点击行
  const customRow = (record: questionType) => {
    return {
      onClick: () => {
        console.log("record", record);
        let childs = childIds.concat();
        if (!childs.includes(record.id)) {
          childs.push(record.id);
        } else {
          childs = childIds.filter(item => item !== record.id);
        }
        console.log("childs", childs);
        setChildIds(childs);
      }
    };
  };
  const handleCancel = (e: any) => {
    if (e.target.className != "ant-modal-wrap") modalState.isCopy = false;
  };
  const handleOk = () => {
    if (childIds.length && modalState.controlLogic) {
      let data: controlLogicType[] = [];
      for (let i in childIds) {
        data.push({ ...modalState.controlLogic, childId: childIds[i] });
      }
      getCopy(childIds, data);
    }
    modalState.isCopy = false;
  };

  return (
    <Modal title="复制向前关联" width="800px" open={modalState.isCopy} onCancel={handleCancel} onOk={handleOk}>
      <Table
        dataSource={tableData}
        columns={columns}
        pagination={false}
        rowSelection={{ selectedRowKeys: childIds, onChange: record => onSelectChange(record) }}
        onRow={record => customRow(record)}
        scroll={{ y: 500 }}
        bordered
        rowKey="id"
        className="copy-table"
      />
    </Modal>
  );
}

export default observer(ConcernCopy);
